package ro.pub.cs.ncit.webviewer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

	private EditText address;
	private Button goButton;
	private WebView webPage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		/*if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}*/
		
		address = (EditText)findViewById(R.id.address);
		goButton = (Button)findViewById(R.id.go_button);
		webPage = (WebView)findViewById(R.id.web_view);
		webPage.getSettings().setJavaScriptEnabled(true);
		
		goButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loadWebPage();
			}
		});
	}
	
	public void loadWebPage(){
		WebDownloader downloader = new WebDownloader();
		downloader.setTaskListener(new TaskListener() {
			
			@Override
			public void onTaskComplete(String result) {
				webPage.loadData(result, "text/html", "UTF-8");
			}
		});
		downloader.execute(address.getText().toString());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
